package com.example.coursehub.exception;

import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;

import java.util.HashMap;
import java.util.Map;

@ControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(RuntimeException.class)
    public ResponseEntity<Map<String, Object>> handleRuntimeException(RuntimeException e) {
        Map<String, Object> response = new HashMap<>();
        // 处理特定的"找不到资料"异常
        if (e.getMessage() != null && e.getMessage().equals("找不到资料")) {
            response.put("error", "Resource not found");
            response.put("status", 500);
            return ResponseEntity.status(500)
                    .header("Content-Type", "application/json")
                    .body(response);
        }
        // 处理其他RuntimeException
        response.put("error", "Internal Server Error");
        response.put("status", 500);
        response.put("message", e.getMessage());
        return ResponseEntity.status(500)
                .header("Content-Type", "application/json")
                .body(response);
    }

    // 可以添加更多特定异常的处理方法
    @ExceptionHandler(Exception.class)
    public ResponseEntity<Map<String, Object>> handleGeneralException(Exception e) {
        Map<String, Object> response = new HashMap<>();
        response.put("error", "Internal Server Error");
        response.put("status", 500);
        response.put("message", e.getMessage());
        return ResponseEntity.status(500)
                .header("Content-Type", "application/json")
                .body(response);
    }
}
